<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>统计词频</title>
    <style>
        body{
            text-align: center;
        }
        .textarea-wrap{
            width: 800px;
            height: 600px;
            background: aliceblue;
            margin: 20px auto;
        }
        #input-text{
            width: 100%;
            height: 100%;

        }
        .res{
            width: 800px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
        }
        .button-cal{
            margin: 20px auto;
            border: 1px solid #ECECEC;
            width: 200px;
            cursor: pointer;
        }
    </style>
</head>
<body>
<div class="textarea-wrap">
    <textarea id="input-text" name="content"  placeholder="请输入要分析的英文文章"></textarea>
</div>
<div class="button-cal" >计算</div>
<div class="res">

    <div class="res-label">一共：</div>
    <div id="res-number"></div>
    <div class="res-label">前五：</div>
    <div id="res-top5"></div>
    <div class="res-label">后五：</div>
    <div id="res-last5"></div>
</div>
<script src="tools/lodash.js"></script>
<script src="tools/jquery.js"></script>
<script>
   $(document).ready(function () {
       function reduceByKey(tuples,reduceCallback) {
           let grouped=_.groupBy(tuples,tuple=>tuple[0]);
           return _.toPairs(_.mapValues(grouped,tuples=>_.chain(tuples).map(tuple=>tuple[1]).reduce(reduceCallback).value()))
       }
      function sortByDesc(arr,index){
           return arr.sort((b,a)=>a[index]-b[index]);
       };
       $(".button-cal").click(function () {
          let content=$("#input-text").val();
          let words=content.toLowerCase().match(/\w+/g);
          $("#res-number").html(words.length);
           let tuples=words.map(function (word) {
               return [word,1]
           });
           let wordsCountResult=reduceByKey(tuples,(left,right)=>left+right)
           let sorted= sortByDesc(wordsCountResult,1)
           let top5=_.take(sorted,5).map(tuple=>tuple[0]);
           $("#res-top5").html(top5.join(","));
           let minimal5=_.takeRight(sorted,5).map(tuple=>tuple[0]);
           $("#res-last5").html(minimal5.join(" , "));
       })

   })
</script>
</body>
</html>